<?php

namespace helper\sina;

use helper\Client;

class Weibo
{
    private array $config;

    /**
     * @var Client
     */
    protected Client $client;

    /**
     * 初始化
     * @param array $config
     */
    public function __construct(array $config)
    {
        $this->config = [
            'client_id' => $config['client_id'],
            'client_secret' => $config['client_secret'],
            'redirect_uri' => urlencode($config['redirect_uri'])
        ];
        $this->client = new Client(['base_uri' => 'https://api.weibo.com/', 'timeout' => 30]);
    }

    public function getCode()
    {
        return "https://api.weibo.com/oauth3/authorize?client_id={$this->config['client_id']}&response_type=code&redirect_uri={$this->config['redirect_uri']}";
    }

    /**
     * 获取access_token
     * @param string $code
     * @return mixed
     */
    public function getAccessToken(string $code)
    {
        $uri = "oauth3/access_token?client_id={$this->config['client_id']}&client_secret={$this->config['client_secret']}&grant_type=authorization_code&redirect_uri={$this->config['redirect_uri']}&code=$code";
        $response = $this->client->post($uri);
        return $response->getBody();
    }

    /**
     * 获取用户信息
     * @param array $token
     * @return mixed
     */
    public function getUserInfo(array $token)
    {
        $uri = "/2/users/show.json?access_token={$token['access_token']}&uid={$token['uid']}";
        $response = $this->client->get($uri);
        return $response->getBody();
    }
}